package com.etc.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.etc.entity.Admin;
import com.etc.entity.UserInfo;
import com.etc.service.UserInfoService;
import com.etc.service.impl.UserInfoServiceImpl;
import com.etc.util.AesLoUtil;
import com.etc.util.DESDemo;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 登录页面控制类
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserInfoService userInfoService = new UserInfoServiceImpl();
	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String op = request.getParameter("op");
		if("login".equals(op)) {
			try {
				doLogin(request,response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 接收请求参数
		String accountNumber = request.getParameter("accountNumber");
		String rememberme = request.getParameter("rememberme");
		String password = request.getParameter("password");
		// 调用业务层 返回用户对象
		UserInfo userInfo = userInfoService.login(accountNumber,DESDemo.encrypt(AesLoUtil.Decrypt(password)));
		//创建会话对象
		HttpSession session = request.getSession();
		StringBuilder sBuilder = new StringBuilder();
		if (userInfo != null) {
			//将用户存在会话中
			session.setAttribute("USER_LOGIN", userInfo);
			sBuilder.append("登录成功");
			//判断是否保存账号密码
			if("rememberme".equals(rememberme)) {
				// 1.创建cookie
				Cookie cookie = new Cookie("rememberMe", accountNumber+"="+password);
				// 2.设置过期时间
				cookie.setMaxAge(60*60*24*7); // 7天
				// 3.将cookie添加到响应头中
				response.addCookie(cookie);
			}
		}else {
			sBuilder.append("登录失败");
		}
		
		// 响应
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(sBuilder.toString());
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write(json);
	}

}
